const app = getApp();
const api = require('../../utils/api');

var animation = {};

Page({
    data: {
        id: '',
        keywords: '',
        isFocus: false, //搜索框聚焦
        showSearchResult: false,

        sortMethod: '', //排序方式
        sortTypeList: [
            {id: 'price', name: '价格', sortName: '', sortTpye: ''},
            {id: 'member_price', name: '会员价', sortName: '', sortTpye: ''},
            {id: 'coupon_amount', name: '券价格', sortName: '', sortTpye: ''},
        ],

        productList: [], //商品列表
        pageNum: 1,
        pageSize: 10,
        total: 0,
        noContent: false,
        isFinished: false, //加载结束

        shopcartList: [], //购物车列表
        shopcartListForRecord: [], //用于记录的购物车列表
        shopcartNumber: 0, //购物车商品数量

        currentItem: {}, //当前操作项
        currentItemIndex: 0, //当前操作项下标
        productDetailAnimation: {}, //商品详情弹窗的动画效果
        isShowProductDetail: false,
        isShowLayer: false, //弹窗遮罩层
        isPreview: false,
    },
    onLoad(options) {
        this.setData({
            id: options.id ? options.id : '',
            isFocus: true,
        });
        this.initData();
    },
    onShow() {
        // 防止图片预览刷新页面
        if(!this.data.isPreview) {
            //初始化动画
            animation = wx.createAnimation({
                duration: 500,
                timingFunction: 'ease-out',
            });
        }
    },

    initData() { //初始化页面数据
        this.getShopcartList();
    },
    getShopcartList() { //获取购物车列表
        api.post('/order/cart/list')
            .then(res => {
                let list = res;
                let recordList = [];

                if(this.data.shopId) { //有店铺id的情况，只保存当前店铺的购物车
                    list.forEach(item => {
                        if(item.shopId == this.data.shopId) {
                            item.detailList.forEach(pro => {
                                recordList.push({
                                    id: pro.id,
                                    skuId: pro.productSkuSaleId,
                                    quantity: pro.quantity
                                })
                            })
                        }
                    });
                } else { //没店铺id，全部保存
                    list.forEach(item => {
                        item.detailList.forEach(pro => {
                            recordList.push({
                                id: pro.id,
                                skuId: pro.productSkuSaleId,
                                quantity: pro.quantity
                            })
                        })
                    });
                }
                
                this.setData({
                    shopcartList: list,
                    shopcartListForRecord: recordList,
                });

                let summary = 0;
                recordList.forEach(item => {
                    summary = summary + item.quantity;
                });
                this.setData({
                    shopcartNumber: summary,
                });
            })
    },
    dealShopcartSummary() { //计算购物车商品数量
        let summary = 0;
        this.data.shopcartListForRecord.forEach(item => {
            summary = summary + item.quantity;
        });
        this.setData({
            shopcartNumber: summary,
        });
        app.globalData.isRefreshShopcart = true;
    },

    searchProduct() { //搜索当前店铺商品
        let params = {
            shopId: this.data.id,
            sortMethod: this.data.sortMethod,
            keyword: this.data.keywords,
            pageNum: this.data.pageNum,
            pageSize: this.data.pageSize
        }
        api.post(`/product/list`, params)
            .then(res => {
                let list = res.content;
                list.forEach(item => {
                    item.price = item.price.toFixed(2);
                });
                let newList = [...this.data.productList, ...list];
                this.setData({
                    productList: this.dealProductSelect(newList),
                    total: res.total,
                    showSearchResult: true
                });

                //是否无内容标识
                if(this.data.productList.length == 0) {
                    this.setData({
                        noContent: true
                    })
                } else {
                    this.setData({
                        noContent: false
                    });
                }
                //是否加载完毕标识
                if(this.data.productList.length >= this.data.total) {
                    this.setData({
                        isFinished: true
                    })
                } else {
                    this.setData({
                        isFinished: false
                    })
                }
                wx.stopPullDownRefresh();
            })
    },
    dealProductSelect(list) { //初始化商品数量
        let dealList = list;
        let shopcartList = this.data.shopcartListForRecord;
        
        dealList.forEach(item => {
            let index = shopcartList.findIndex(i => {
                return i.skuId == item.id;
            });

            if(index > -1) {
                item.quantity = shopcartList[index].quantity;
            } else {
                item.quantity = 0;
            }
        });
        // console.log(dealList)
        return dealList;
    },

    sortList(e) { //列表排序
        let item = e.currentTarget.dataset.item;
        let newName = ''; //控制箭头方向
        let newType = ''; //提交用参数
        if(item.sortName == 'desc') { //原来是降序
            newName = 'asc';
            newType = 'asc';
        } else if(item.sortName == 'asc') { //原来是升序
            newName = '';
            newType = '';
        } else { //原来是默认状态
            newName = 'desc';
            newType = 'desc';
        }
        //整理选项
        let list = this.data.sortTypeList;
        list.forEach(i => {
            if(i.id == item.id) {
                i.sortName = newName;
                i.sortTpye = newType;
            }
        });
        let resultList = [];
        let resultText = '';
        list.forEach(i => {
            if(i.sortName) {
                resultList.push(i);
            }
        });
        console.log(resultList)
        resultList.forEach((i, index) => {
            resultText = resultText + i.id + ':' + i.sortTpye + (index == resultList.length-1 ? '' : ',');
        });
        
        this.setData({
            sortTypeList: list,
            sortMethod: resultText,
            productList: [],
            pageNum: 1,
            total: 0,
            isFinished: false,
        });
        this.searchProduct();
    },

    //搜索商品
    bindInput(e) {
        let val = e.detail.value;
        this.setData({
            keywords: val
        });
    },
    clearKeywords() { //清除搜索关键字
        this.setData({
            keywords: '',
            isFocus: true
        });
    },
    submitSearch() { //提交搜索
        if(!this.data.keywords) {
            wx.showToast({
                title: '请输入搜索商品名称',
                icon: 'none'
            });
            return;
        }
        //重置排序选项
        let list = this.data.sortTypeList;
        list.forEach(i => {
            i.sortName = '';
            i.sortTpye = '';
        });
        this.setData({
            sortTypeList: list,
            sortMethod: '',
            productList: [],
            pageNum: 1,
            total: 0,
            isFinished: false,
        });

        this.searchProduct();
    },

    //商品操作
    quantityPlus(e) { //数量加
        let index = e.currentTarget.dataset.index;
        let number = this.data.productList[index].quantity;
        this.setData({
            [`productList[${index}].quantity`]: number + 1
        });

        if(number == 0) {
            //第一次选数量，添加购物车
            this.addShopcart(index);
        } else {
            //其他，修改购物车数量
            this.dealShopcartQuantity(index);
        }
    },
    quantityMinus(e) { //数量减
        let index = e.currentTarget.dataset.index;
        let number = this.data.productList[index].quantity;
        this.setData({
            [`productList[${index}].quantity`]: number - 1
        });
        if(this.data.productList[index].quantity == 0) {
            this.removeShopcart(index);
        } else {
            this.dealShopcartQuantity(index, -1);
        }
    },

    //购物车操作
    addShopcart(index, quantity = 0) { //添加购物车
        let params = {
            skuSaleId: this.data.productList[index].id
        }
        api.post('/order/cart/add', params)
            .then(res => {
                let list = this.data.shopcartListForRecord;
                list.push({
                    id: res,
                    skuId: this.data.productList[index].id,
                    quantity: quantity ? quantity : this.data.productList[index].quantity
                });
                this.setData({
                    shopcartListForRecord: list
                });
                
                if(quantity > 1) {
                    wx.showToast({
                        title: '添加购物车成功',
                        icon: 'none'
                    });
                    this.dealShopcartQuantity(index, quantity-1);
                } else {
                    wx.showToast({
                        title: '添加购物车成功',
                        icon: 'none'
                    });
                    this.dealShopcartSummary();
                    this.closeProductDetail();
                }
            })
    },
    dealShopcartQuantity(index, quantity = 1) { //修改购物车数量
        let list = this.data.shopcartListForRecord;
        let i = list.findIndex(item => {
            return item.skuId == this.data.productList[index].id
        })
        api.post(`/order/cart/quantity?id=${this.data.shopcartListForRecord[i].id}&diffQuantity=${quantity}`)
            .then(() => {
                list.forEach(item => {
                    if(item.skuId == this.data.productList[index].id) {
                        item.quantity = this.data.productList[index].quantity;
                    }
                });
                this.setData({
                    shopcartListForRecord: list
                });

                this.dealShopcartSummary();
                this.closeProductDetail();
            })
    },
    removeShopcart(index) { //删除购物车商品
        let list = this.data.shopcartListForRecord;
        let i = list.findIndex(item => {
            return item.skuId == this.data.productList[index].id
        })
        api.post(`/order/cart/remove?ids=${list[i].id}`)
            .then(() => {
                list.splice(i, 1);
                this.setData({
                    shopcartListForRecord: list
                });

                wx.showToast({
                    title: '删除成功',
                    icon: 'none'
                });
                this.dealShopcartSummary();
                this.closeProductDetail();
            })
    },
    gotoShopcart() { //查看购物车
        wx.switchTab({
            url: '/pages/shopcart/shopcart',
        });
    },

    //弹窗操作
    viewProductDetail(e) { //查看商品详情
        let item = e.currentTarget.dataset.item;
        let index = e.currentTarget.dataset.index;
        animation.bottom('0').step();
        this.setData({
            productDetailAnimation: animation.export(),
            isShowProductDetail: true,
            isShowLayer: true
        });

        api.post(`/product/detail?id=${item.id}&shopId=${this.data.id}`)
            .then(res => {
                let item = res;
                item.sku.price = item.sku.price.toFixed(2);
                item.originalQuantity = this.data.productList[index].quantity; //初始数量
                item.quantity = this.data.productList[index].quantity ? this.data.productList[index].quantity : 1; //显示数量
                item.selected = this.data.productList[index].quantity ? true : false; //是否已加入过购物车
                this.setData({
                    currentItem: item,
                    currentItemIndex: index,
                })
            })
    },
    closeProductDetail() { //关闭商品详情
        if(!this.data.isShowProductDetail) {
            return;
        }
        animation.bottom('-100%').step();
        this.setData({
            productDetailAnimation: animation.export(),
            isShowProductDetail: false,
            isShowLayer: false
        });
    },
    previewImage(e) { //查看商品大图
        this.setData({
            isPreview: true, //防止页面刷新
        });
        let current = e.currentTarget.dataset.item;
        let url = this.data.currentItem.carouselImageList;
        wx.previewImage({
            current: current, //当前显示图片的http链接
            urls: url, // 需要预览的图片http链接列表
        })
    },
    closeLayer() { //点击遮罩层
        if(this.data.isShowAllFirstCategory) {
            this.closeFirstCategory();
        } else if(this.data.isShowProductDetail) {
            this.closeProductDetail();
        }
    },

    //商品详情操作
    toolbarQuantityPlus() { //数量加
        let number = this.data.currentItem.quantity;
        this.setData({
            [`currentItem.quantity`]: number + 1,
        });
    },
    toolbarQuantityMinus() { //数量减
        let number = this.data.currentItem.quantity;
        if(number == 0) {
            return;
        }
        this.setData({
            [`currentItem.quantity`]: number - 1,
        });
    },
    toolbarAddShopcart() { //加入购物车
        this.setData({
            [`productList[${this.data.currentItemIndex}].quantity`]: this.data.currentItem.quantity
        });

        if(this.data.currentItem.originalQuantity == 0 && this.data.currentItem.quantity) {
            //第一次加购物车
            this.addShopcart(this.data.currentItemIndex, this.data.currentItem.quantity);
        } else if(this.data.currentItem.originalQuantity && this.data.currentItem.quantity == 0) {
            //删除购物车
            this.removeShopcart(this.data.currentItemIndex);
        } else if(this.data.currentItem.originalQuantity && this.data.currentItem.quantity != this.data.currentItem.originalQuantity) {
            //修改购物车数量
            this.dealShopcartQuantity(this.data.currentItemIndex, this.data.currentItem.quantity - this.data.currentItem.originalQuantity);
        } else {
            this.closeProductDetail();
        }
    },

    onPullDownRefresh() {
        //下拉刷新
        this.setData({
            productList: [],
            pageNum: 1,
            total: 0,
            isFinished: false,
        });
        this.submitSearch();
    },
    onReachBottom() {
        //加载更多
        if(!this.data.isFinished) {
            this.setData({
                pageNum: this.data.pageNum+1,
            });
            
            setTimeout(() => {
                this.searchProduct();
            }, 800);
        }
    },
})